package com.tree.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tree.backend.entity.dto.EnterpriseDTO;
import com.tree.backend.entity.dto.EnterpriseQueryDTO;
import com.tree.backend.entity.pojo.Enterprise;
import com.tree.backend.entity.pojo.User;
import com.tree.backend.entity.vo.EnterpriseListVO;
import com.tree.backend.entity.vo.EnterpriseStatsVO;
import com.tree.backend.entity.vo.EnterpriseVO;
import com.tree.backend.mapper.EnterpriseMapper;
import com.tree.backend.mapper.UserMapper;
import com.tree.backend.service.IEnterpriseService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * <p>
 * 企业表 服务实现类
 * </p>
 *
 * @author tree
 * @since 2025-11-06
 */
@Service
@RequiredArgsConstructor

public class EnterpriseServiceImpl extends ServiceImpl<EnterpriseMapper, Enterprise> implements IEnterpriseService {

    private final UserMapper userMapper;

    @Override
    public EnterpriseStatsVO getEnterpriseStats() {
        EnterpriseStatsVO statsVO = new EnterpriseStatsVO();
        // 获取企业总数
        Long totalCount = this.count();
        statsVO.setTotalCount(totalCount);

        // 获取待审核企业数
        Long pendingCount = this.count(new QueryWrapper<Enterprise>().eq("status", 0));
        statsVO.setPendingCount(pendingCount);

        // 获取正常企业数
        Long normalCount = this.count(new QueryWrapper<Enterprise>().eq("status", 1));
        statsVO.setNormalCount(normalCount);

        // 获取审核失败企业数
        Long failedCount = this.count(new QueryWrapper<Enterprise>().eq("status", 2));
        statsVO.setFailedCount(failedCount);

        // 获取禁用企业数
        Long disabledCount = this.count(new QueryWrapper<Enterprise>().eq("status", 3));
        statsVO.setDisabledCount(disabledCount);

        return statsVO;
    }

    @Override
    public IPage<EnterpriseListVO> getEnterpriseList(EnterpriseQueryDTO queryDTO) {
        // 构建查询条件
        QueryWrapper<Enterprise> queryWrapper = new QueryWrapper<>();

        // 按名称搜索
        if (StringUtils.hasText(queryDTO.getName())) {
            queryWrapper.like("name", queryDTO.getName());
        }

        // 按联系人姓名搜索
        if (StringUtils.hasText(queryDTO.getContactName())) {
            queryWrapper.like("contact_name", queryDTO.getContactName());
        }

        // 按企业地址搜索
        if (StringUtils.hasText(queryDTO.getAddress())) {
            queryWrapper.like("address", queryDTO.getAddress());
        }

        // 按状态筛选
        if (queryDTO.getStatus() != null) {
            queryWrapper.eq("status", queryDTO.getStatus());
        }

        // 分页查询
        Page<Enterprise> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        IPage<Enterprise> enterprisePage = this.page(page, queryWrapper);

        // 转换为VO对象
        return enterprisePage.convert(enterprise -> {
            EnterpriseListVO vo = new EnterpriseListVO();
            BeanUtils.copyProperties(enterprise, vo);
            vo.setStatusText(getStatusText(enterprise.getStatus()));
            return vo;
        });
    }

    @Override
    public EnterpriseVO getEnterpriseDetail(Long id) {
        Enterprise enterprise = this.getById(id);
        if (enterprise == null) {
            return null;
        }

        EnterpriseVO vo = new EnterpriseVO();
        BeanUtils.copyProperties(enterprise, vo);
        vo.setStatusText(getStatusText(enterprise.getStatus()));
        return vo;
    }

    @Override
    public Enterprise addEnterprise(EnterpriseDTO enterpriseDTO) {
        Enterprise enterprise = new Enterprise();
        BeanUtils.copyProperties(enterpriseDTO, enterprise);

        // 新增企业默认状态为待审核
        enterprise.setStatus(0);
        enterprise.setCreateTime(LocalDateTime.now());
        enterprise.setUpdateTime(LocalDateTime.now());

        this.save(enterprise);
        return enterprise;
    }

    @Override
    public Enterprise updateEnterprise(Long id, EnterpriseDTO enterpriseDTO) {
        Enterprise enterprise = this.getById(id);
        if (enterprise == null) {
            return null;
        }

        BeanUtils.copyProperties(enterpriseDTO, enterprise);
        enterprise.setId(id);
        enterprise.setUpdateTime(LocalDateTime.now());

        this.updateById(enterprise);
        return enterprise;
    }

    @Override
    @Transactional
    public void deleteEnterprise(Long id) {
        userMapper.delete(new LambdaQueryWrapper<User>().eq(User::getEnterpriseId, id));
        this.removeById(id);
    }

    @Override
    @Transactional
    public void auditEnterprise(Long id, Integer status, String reason) {
        Enterprise enterprise = this.getById(id);
        if (enterprise == null) {
            return;
        }

        // 更新审核状态
        enterprise.setStatus(status);
        enterprise.setUpdateTime(LocalDateTime.now());

        // 如果是审核成功，则自动生成企业的账号
        if (status == 1) {
            userMapper.insert(User.builder()
                    .username(enterprise.getContactPhone())
                    .password("123456") // 默认密码
                    .enterpriseId(enterprise.getId())
                    .userType(2)
                    .status(1)
                    .phone(enterprise.getContactPhone())
                    .email(enterprise.getContactEmail())
                    .build());
        }

        this.updateById(enterprise);
    }

    /**
     * 获取状态对应的文本描述
     */
    private String getStatusText(Integer status) {
        if (status == null) {
            return "";
        }
        return switch (status) {
            case 0 -> "待审核";
            case 1 -> "正常";
            case 2 -> "审核失败";
            case 3 -> "禁用";
            default -> "未知状态";
        };
    }
}
